package cn.jluzh.blog.modules.article.service.impl;

import cn.jluzh.blog.mapper.SysArticleMapper;
import cn.jluzh.blog.modules.article.entity.SysArticle;
import cn.jluzh.blog.modules.article.entity.SysArticleArchives;
import cn.jluzh.blog.modules.article.entity.SysArticleTag;
import cn.jluzh.blog.modules.article.service.ArticleService;
import cn.jluzh.blog.modules.category.entity.SysCategory;
import cn.jluzh.blog.modules.category.service.impl.CategoryServiceImpl;
import cn.jluzh.blog.modules.tag.entity.SysTag;
import cn.jluzh.blog.modules.tag.service.impl.TagServiceImpl;
import cn.jluzh.blog.modules.user.entity.SysUser;
import cn.jluzh.blog.modules.user.service.impl.UserServiceImpl;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 文章表
 *
 * @author liangfeihu
 * @email liangfhhd@163.com
 * @date 2018-07-04 15:00:55
 */
@Service
public class ArticleServiceImpl extends ServiceImpl<SysArticleMapper, SysArticle> implements ArticleService {
    @Autowired
    SysArticleMapper sysArticleMapper;
    @Autowired
    CategoryServiceImpl categoryService;
    @Autowired
    TagServiceImpl tagService;
    @Autowired
    UserServiceImpl userService;
    @Autowired
    ArticleTagServiceImpl articleTagService;

    @Override
    public List<SysArticle> getAllArticle() {
        List<SysArticle> articleList = sysArticleMapper.selectList(null);
        return articleList;
    }

    @Override
    public List<SysArticle> getArtByCateId(Integer categoryId) {
        return sysArticleMapper.getArtByCateId(categoryId);
    }

    @Override
    public List<SysArticle> getArtByTagId(Integer tagId){
        List<SysArticle> artByTagId = sysArticleMapper.getArtByTagId(tagId);
        return artByTagId;
    }

    @Override
    public JSONObject getArticleDetailAndAddViewNum(Long id) {
        SysArticle article = sysArticleMapper.selectById(id);
        JSONObject object = new JSONObject();
        object.put("id", article.getId());
        object.put("title", article.getTitle());
        object.put("summary", article.getSummary());
        object.put("createTime", new DateTime(article.getCreateTime()).toString("yyyy-MM-dd HH:mm:ss"));

        article.setViewNum(article.getViewNum() + 1);
        object.put("viewNum", article.getViewNum());
        object.put("commentNum", article.getCommentNum());
        object.put("content", article.getContent());

        SysCategory categoryById = categoryService.getCategoryById(article.getCategoryId());
        object.put("category",categoryById);

        List<SysTag> tagByArtId = tagService.getTagByArtId(article.getId());
        object.put("tags", tagByArtId);

        // 2、文章作者信息
        SysUser sysUser = userService.getById(article.getUserId());
        JSONObject user = new JSONObject();
        user.put("id", sysUser.getId());
        user.put("avatarName", sysUser.getAvatarName());
        user.put("avatarUrl", sysUser.getAvatarUrl());
        user.put("nickname", sysUser.getNickname());
        object.put("author", user);

        return object;
    }

    @Override
    public List<SysArticleArchives> queyArticleArchives(int limit) {
        return sysArticleMapper.queyArticleArchives(limit);
    }

    @Override
    public List<SysArticle> getArtByDate(String year,String month) {
        QueryWrapper<SysArticle> wrapper = new QueryWrapper<>();
        wrapper.eq("year(create_time)", year);
        wrapper.eq("month(create_time)", month);
        List<SysArticle> sysArticles = sysArticleMapper.selectList(wrapper);
        return sysArticles;
    }

    @Override
    public Long updateOneArticle(SysUser user, SysArticle article, JSONObject json) {
        Long id = article.getId();
        Map<Integer, String> map = getTagMapInfos();

        // 1、更新文章信息
        article.setTitle(json.getString("title"));
        article.setSummary(json.getString("summary"));

        JSONObject body = json.getJSONObject("body");
        article.setContent(body.getString("content"));
        article.setContentHtml(body.getString("contentHtml"));

        JSONObject category = json.getJSONObject("category");
        if (article.getCategoryId().intValue() != category.getInteger("id").intValue()) {
            article.setCategoryId(category.getInteger("id"));
        }

        // 2、获取文章对应的标签信息
        List<SysArticleTag> articleTagList = new ArrayList<>();
        StringBuilder tagStr = new StringBuilder();
        JSONArray tags = json.getJSONArray("tags");
        for (int i = 0; i < tags.size(); i++ ) {
            Integer tagId = tags.getJSONObject(i).getInteger("id");
            if (i != 0){
                tagStr.append(",");
            }
            tagStr.append(map.get(tagId));

            SysArticleTag articleTag = new SysArticleTag();
            articleTag.setArticleId(id);
            articleTag.setTagId(tagId);
            articleTag.setCreateTime(new Date());
            articleTag.setUpdateTime(new Date());
            articleTagList.add(articleTag);
        }
        article.setTags(tagStr.toString());

        article.setUpdateTime(new Date());
        article.setUserId(user.getId());
        article.setNickname(user.getNickname());
        this.updateById(article);

        // 3、删除之前的文章标签信息
        QueryWrapper<SysArticleTag> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("article_id", id);
        articleTagService.remove(queryWrapper);

        // 4、更新文章标签信息
        articleTagService.saveBatch(articleTagList);

        return id;
    }

    @Override
    public Long addOneArticle(SysUser user, JSONObject json) {
        Map<Integer, String> maps = getTagMapInfos();

        // 1、保存文章信息
        SysArticle article = new SysArticle();
        article.setUserId(user.getId());
        article.setNickname(user.getNickname());
        article.setCommentNum(0);
        article.setViewNum(0);
        article.setCreateTime(new Date());
        article.setUpdateTime(new Date());
        article.setWeight(0);
        article.setTitle(json.getString("title"));
        article.setSummary(json.getString("summary"));

        JSONObject body = json.getJSONObject("body");
        article.setContent(body.getString("content"));
        article.setContentHtml(body.getString("contentHtml"));

        // 2、设置分类信息
        JSONObject category = json.getJSONObject("category");
        article.setCategoryId(category.getInteger("id"));

        // 3、设置标签信息
        JSONArray tags = json.getJSONArray("tags");
        StringBuilder tagStr = new StringBuilder();
        for (int i = 0; i < tags.size(); i++ ) {
            Integer tagId = tags.getJSONObject(i).getInteger("id");
            if (i != 0){
                tagStr.append(",");
            }
            tagStr.append(maps.get(tagId));
        }
        article.setTags(tagStr.toString());

        // 4、插入文章信息
        this.save(article);

        Long id = article.getId();

        // 5、插入文章对应的标签信息
        List<SysArticleTag> articleTagList = new ArrayList<>();
        for (int i = 0; i < tags.size(); i++ ) {
            Integer tagId = tags.getJSONObject(i).getInteger("id");
            SysArticleTag articleTag = new SysArticleTag();
            articleTag.setArticleId(id);
            articleTag.setTagId(tagId);
            articleTag.setCreateTime(new Date());
            articleTag.setUpdateTime(new Date());
            articleTagList.add(articleTag);
        }
        articleTagService.saveBatch(articleTagList);

        return id;
    }

    @Override
    public List<SysArticle> getAllArticleByTitle(String query) {
        List<SysArticle> allArticleByTitle = sysArticleMapper.getAllArticleByTitle(query);
        return allArticleByTitle;
    }

    /**
     * 获取标签Map数据
     *
     * @return
     */
    private  Map<Integer, String> getTagMapInfos() {
        List<SysTag> tags = tagService.list();
        Map<Integer, String> map = new HashMap<>();
        for (SysTag tag: tags){
            map.put(tag.getId(), tag.getTagName());
        }
        return map;
    }
}
